package com.cloudlegal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudlegal.common.PageQuery;
import com.cloudlegal.common.PageResult;
import com.cloudlegal.entity.BizClient;
import com.cloudlegal.mapper.BizClientMapper;
import com.cloudlegal.service.BizClientService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户服务实现类
 * 
 * @author CloudLegal Team
 * @since 2024-01-01
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BizClientServiceImpl extends ServiceImpl<BizClientMapper, BizClient> implements BizClientService {

    @Override
    public PageResult<BizClient> getClientPage(PageQuery pageQuery, Integer clientType, Integer status) {
        Page<BizClient> page = new Page<>(pageQuery.getPage(), pageQuery.getSize());
        IPage<BizClient> result = baseMapper.selectClientPage(page, pageQuery.getKeyword(), clientType, status);
        return PageResult.of(result);
    }

    @Override
    public List<BizClient> getClientList(String keyword, Integer clientType, Integer status) {
        return baseMapper.selectClientList(keyword, clientType, status);
    }

    @Override
    public BizClient getByClientName(String clientName) {
        return baseMapper.selectByClientName(clientName);
    }

    @Override
    public BizClient getByCreditCode(String creditCode) {
        return baseMapper.selectByCreditCode(creditCode);
    }

    @Override
    public boolean createClient(BizClient client) {
        // 验证客户名称唯一性
        if (existsByClientName(client.getClientName(), null)) {
            throw new RuntimeException("客户名称已存在");
        }
        
        // 验证统一社会信用代码唯一性（如果是企业客户）
        if (client.getClientType() == 2 && StringUtils.hasText(client.getCreditCode())) {
            if (existsByCreditCode(client.getCreditCode(), null)) {
                throw new RuntimeException("统一社会信用代码已存在");
            }
        }
        
        // 设置默认状态
        if (client.getStatus() == null) {
            client.setStatus(1);
        }
        
        return save(client);
    }

    @Override
    public boolean updateClient(BizClient client) {
        BizClient existingClient = getById(client.getId());
        if (existingClient == null) {
            throw new RuntimeException("客户不存在");
        }
        
        // 验证客户名称唯一性
        if (!existingClient.getClientName().equals(client.getClientName()) && 
            existsByClientName(client.getClientName(), client.getId())) {
            throw new RuntimeException("客户名称已存在");
        }
        
        // 验证统一社会信用代码唯一性（如果是企业客户）
        if (client.getClientType() == 2 && StringUtils.hasText(client.getCreditCode()) &&
            !client.getCreditCode().equals(existingClient.getCreditCode()) &&
            existsByCreditCode(client.getCreditCode(), client.getId())) {
            throw new RuntimeException("统一社会信用代码已存在");
        }
        
        return updateById(client);
    }

    @Override
    public boolean deleteClient(Long clientId) {
        // 检查是否有关联的案件或合同
        // TODO: 实现业务约束检查
        return removeById(clientId);
    }

    @Override
    public boolean batchDeleteClients(List<Long> clientIds) {
        // 检查是否有关联的案件或合同
        // TODO: 实现业务约束检查
        return removeByIds(clientIds);
    }

    @Override
    public boolean updateClientStatus(Long clientId, Integer status) {
        BizClient client = new BizClient();
        client.setId(clientId);
        client.setStatus(status);
        return updateById(client);
    }

    @Override
    public boolean batchUpdateClientStatus(List<Long> clientIds, Integer status) {
        return baseMapper.batchUpdateStatus(clientIds, status) > 0;
    }

    @Override
    public boolean existsByClientName(String clientName, Long excludeId) {
        LambdaQueryWrapper<BizClient> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BizClient::getClientName, clientName);
        if (excludeId != null) {
            wrapper.ne(BizClient::getId, excludeId);
        }
        return count(wrapper) > 0;
    }

    @Override
    public boolean existsByCreditCode(String creditCode, Long excludeId) {
        if (!StringUtils.hasText(creditCode)) {
            return false;
        }
        
        LambdaQueryWrapper<BizClient> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BizClient::getCreditCode, creditCode);
        if (excludeId != null) {
            wrapper.ne(BizClient::getId, excludeId);
        }
        return count(wrapper) > 0;
    }

    @Override
    public Map<String, Object> getClientStats() {
        Map<String, Object> stats = baseMapper.selectClientStats();
        if (stats == null) {
            stats = new HashMap<>();
            stats.put("total", count());
            stats.put("active", baseMapper.countClients(1));
            stats.put("inactive", baseMapper.countClients(0));
        }
        return stats;
    }

    @Override
    public List<Map<String, Object>> getClientStatsByType() {
        return baseMapper.countByClientType();
    }

    @Override
    public List<Map<String, Object>> getClientStatsByIndustry(Integer limit) {
        return baseMapper.countByIndustry(limit);
    }

    @Override
    public List<BizClient> getRecentClients(Integer limit) {
        return baseMapper.selectRecentClients(limit);
    }
}
